<!DOCTYPE html>
<html lang="zh-cn">
<head>
  
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
  <title>
重拾C语言之数组初始化 |
穷折腾</title>
  <link rel="stylesheet" href="/static/css/style.css" />
  <link rel="stylesheet" href="/static/css/pygments.css" />
  <link rel="alternate" type="application/rss+xml" title="RSS" href="http://blog.zorro.im/rss.xml" />
  <link rel="icon" type="image/png" href="/static/img/favicon.png">
</head>
<body>
    <div class="page-wrap">
        <section class="main-header regular">
            <div class="vertical-container">
                <div class="wrapper clearfix">
                    <header>
                        <a href="/">
                            <h1 id="main-title">穷折腾</h1>
                            <h2 id="main-subtitle">zqqf16 的个人博客</h2>
                        </a>
                    </header>
                    <nav id="main-nav" role="navigation">
                        <a href="/" class="selected">主页</a>
                        <a href="/posts/about.html" class="">关于</a>
                        <a href="https://github.com/zqqf16">Github</a>
                    </nav>
                </div>
            </div>
        </section>
        <section class="main-content">
            
<article class="main-content">
    <div class="wrapper">
        <header class="section-header">
            <h1 class="section-title">重拾C语言之数组初始化</h1>
            <span class="section-subtitle"><time datetime="2013-05-26" pubdate="">2013-05-26</time></span>
        </header>
        <section class="post-content">
        	<p>记得刚工作的时候，每次用字符串数组都是小心翼翼。当时基本都是这样：</p>
<div class="codehilite"><pre><span class="kt">char</span> <span class="n">str</span><span class="p">[</span><span class="mi">32</span><span class="p">];</span>
<span class="n">memset</span><span class="p">(</span><span class="n">str</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">src</span><span class="p">));</span>
</pre></div>


<p>那时颇为自豪，自认为很少有菜鸟能像我这样注意这些问题。直到后来有一次代码review，在一老鸟面前班门弄斧，结果被他指出来了，说我这样会浪费一次函数调用，直接<code>char str[32] = {0}</code>更好。刚开始我还以为这是一种特殊语句，是把数组的每个元素都赋0。</p>
<p>有一次我想把数组全初始化成1，就直接<code>int list[4] = {1}</code>。结果进引起了一个bug，害得我花了很长时间才找到问题所在——list中除了第一个是1,其它的都是0。于是我决定好好研究一下，争取不再犯这样的错误。</p>
<p>其实，这玩意很简单，简单到不能再简单了，以至于研究完了我都觉得羞愧了。。。</p>
<p>首先，看下面的语句：</p>
<div class="codehilite"><pre><span class="kt">char</span> <span class="n">str</span><span class="p">[</span><span class="mi">4</span><span class="p">]</span> <span class="o">=</span> <span class="p">{</span><span class="sc">&#39;0&#39;</span><span class="p">,</span> <span class="sc">&#39;1&#39;</span><span class="p">,</span> <span class="sc">&#39;2&#39;</span><span class="p">,</span> <span class="sc">&#39;3&#39;</span><span class="p">};</span>
</pre></div>


<p>这是标准的数组初始化方法，字符串数组的每个元素都被赋上初始值（大括号内的个数等于数组长度）。</p>
<p>当大括号内的值小于数组长度的时候，比如：</p>
<div class="codehilite"><pre><span class="kt">char</span> <span class="n">str</span><span class="p">[</span><span class="mi">4</span><span class="p">]</span> <span class="o">=</span> <span class="p">{</span><span class="sc">&#39;0&#39;</span><span class="p">,</span> <span class="sc">&#39;1&#39;</span><span class="p">};</span>
</pre></div>


<p>str[0]和str[1]会被赋上相应的初始值，而剩下的元素会被初始化成0。这基本是没本C语言书里面都会讲到的。</p>
<p>所以，反过来再看看之前的例子：</p>
<div class="codehilite"><pre><span class="kt">int</span> <span class="n">list</span><span class="p">[</span><span class="mi">4</span><span class="p">]</span> <span class="o">=</span> <span class="p">{</span><span class="mi">1</span><span class="p">};</span>
</pre></div>


<p>就是把第一个元素赋1，其他的元素都被初始化成0。</p>
<p>就是这么简单。</p>
        </section>
        <div class="post-nav">
    		<!-- Duoshuo Comment BEGIN -->
<div class="ds-thread"></div>
<script type="text/javascript">
	var duoshuoQuery = {short_name:"zqqf16"};
	(function() {
		var ds = document.createElement('script');
		ds.type = 'text/javascript';ds.async = true;
		ds.src = 'http://static.duoshuo.com/embed.js';
		ds.charset = 'UTF-8';
		(document.getElementsByTagName('head')[0]
		|| document.getElementsByTagName('body')[0]).appendChild(ds);
	})();
</script>
<!-- Duoshuo Comment END -->

    	</div>
    </div>

</article>

        </section>
    </div>
    <footer class="main-footer">
        <div class="vertical-container">
            <div class="wrapper">
                <p class="copy">&copy; zqqf16</p>
            </div>
        </div>
    </footer>
    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
      ga('create', 'UA-41282906-2', 'auto');
      ga('require', 'displayfeatures');
      ga('send', 'pageview');
    </script>
</body>
</html>
